package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author John
 * @date 2022/12/06 0006
 * @apiNote
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求的路径，判断是否登录，登录才放行
        if (request.getURI().getPath().contains("/login_auth")) {
            return chain.filter(exchange);
        }
        //3.从请求头里面获取用户token，如果为空则返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.解析判断token，如果不合法或者过期返回401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int status = AppJwtUtil.verifyToken(claimsBody);
        if (1 == status || 2 == status) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.合法则放行
        return chain.filter(exchange);
    }

    /**
     * 返回一个排序的数字，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
